const app = getApp()
import {
  showMsg
} from '../../../../utils/config.js'
import {
  reqDoorList,
  reqCommandService,
  reqCommand,
  reqBatchDoorSwitch,
  reqFloorById,
  reqDeviceList,
  reqDeviceUserpage,
  reqDeviceData,
  reqDeviceFindInfo
} from '../../../../request/api'
import Dialog from '@vant/weapp/dialog/dialog';

Page({
  data: {
    openDoor: false, //开门告警
    closeDoor: false, //关门告警
    height: '480rpx',
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    currentTab: 0,
    deviceInfo: {},
    dataList: [],
    page: 1,
    isNextPage: true, //是否下一页
    triggered: false, //是否下拉刷新列表
    srcFraredActive: '/statics/images/device/infrared_active.png',
    srcInfraredActive: '/statics/images/device/infrared_inactive.png',
    empty: '/statics/images/empty.png',
    showStatus: false,
    showStatus2: false,
    serviceTypeList: [{
      id: 'work_mode',
      text: '工作模式',
    }, ],
    serviceTypeList2: [{
      id: 'muffling_cmd',
      text: '消音下发',
    }, {
      id: 'temperature_throshold',
      text: '温度阈值设置',
    }, {
      id: 'heartbeat_time',
      text: '心跳周期设置',
    }, {
      id: 'remote_tamper_state_cmd',
      text: '防拆功能控制',
    }, ],
    serviceValueList: [{
      id: 0,
      text: '普通模式',
    }, {
      id: 1,
      text: '实时上报模式',
    }, {
      id: 2,
      text: '活动量统计模式',
    }, {
      id: 3,
      text: '建行模式',
    }, {
      id: 4,
      text: '三小场所模式',
    }, {
      id: 5,
      text: '老人独居模式',
    }, ],
    serviceValueList2: [{
      id: 1,
      text: '消音',
    }, ],
    remote_tamper_state_cmdValue: [{
      id: 0,
      text: '关闭本地防拆声光报警',
    }, {
      id: 1,
      text: '打开本地防拆声光报警',
    }, {
      id: 2,
      text: '禁用防拆功能检测',
    }, ],
    serviceType: "", //标识值
    serviceValue: "", //服务值
    identifier: "", //标识符
    serviceTypename: "",
    serviceValuename: "",
    isProprietor: false,
    deviceData: {},
    commandList: [],
    dataDefinition: [],
    inputType: '1',
    placeholderStr: "1-100",
    num1: 1,
    num2: 100,
    accessToken: "",

    emInfo: {}, //电气设备信息

    orgId2: "",
    Height: "100rpx"
  },
  onShow() {
    this.setData({
      isProprietor: app.globalData.isProprietor,
      orgId2: app.globalData.orgId2,
    })
    if (app.globalData.orgId2 == 0) {
      // 个人
      this.setData({
        Height: '0rpx',
      })
    } else {
      this.setData({
        Height: '100rpx',
      })
    }
    this.gettoken() // 获取token
  },
  onLoad(e) {
    console.log(JSON.parse(e.info));
    let item = JSON.parse(e.info)

    this.getDeviceData(item) //imei查询最新设备数据

    this.getCommandService(item) //指令服务

    this.getDeviceInfo(e)
    if (item.openDoor == 0) {
      this.setData({
        openDoor: false
      })
    } else {
      this.setData({
        openDoor: true
      })
    }
    if (item.closeDoor == 0) {
      this.setData({
        closeDoor: false
      })
    } else {
      this.setData({
        closeDoor: true
      })
    }

  },

  // 获取电气综合测控装置详情
  async getDeviceFindInfo() {
    const res = await reqDeviceFindInfo(this.data.deviceInfo.deviceId);
    if (res.code !== 20000) return showMsg(res.message)
    if (res.data.info.info) {
      const info = JSON.parse(res.data.info.info);
      this.setData({
        emInfo: info
      })
    }
  },
  // 获取token
  gettoken() {
    wx.request({
      url: `https://open.ys7.com/api/lapp/token/get`, //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        appKey: 'd6a1a4287b9a4d78adebaa7bbc8c7125',
        appSecret: '6b9102e6b4ef80beb7067be13d08bd2c',
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log(res);
        this.setData({
          accessToken: res.data.data.accessToken
        })
        //   this.getaddress()//获取视频流
      }
    });
  },
  // 指令服务分页
  async getCommandService(e) {
    console.log(e.protocol);
    const res = await reqCommandService(1, 50, {
      productModel: e.classMark,
      protocol: e.protocol
    })
    if (res.code !== 20000) return showMsg(res.message)
    console.log(res);
    this.setData({
      commandList: res.data.rows
    })
    // 单独判断消音下发功能
    let erasure = false;
    let identifier = ''
    let serviceType = ''
    let serviceValue = ''
    let dataDefinition = ''
    this.data.commandList.forEach(item => {
      if (item.serviceName == '消音下发') {
        erasure = true
        identifier = item.identifier
        serviceType = item.serviceType
        dataDefinition = JSON.parse(item.dataDefinition)
        return;
      }
    })
    if (!erasure) return;
    dataDefinition.forEach(item => {
      if (item.key == '消音') {
        serviceValue = item.value; //指令值
      }
    })
    this.setData({
      erasure,
      identifier,
      serviceType,
      serviceValue
    })
  },
  // 消音下发
  async onErasure() {
    Dialog.confirm({
        title: '温馨提示',
        message: '此操作将对该设备进行消音下发，是否继续？',
      })
      .then(async () => {
        const res = await reqCommand({
          deviceId: this.data.deviceInfo.deviceId,
          imei: this.data.deviceInfo.imei,
          serviceType: this.data.serviceType,
          serviceValue: this.data.serviceValue,
          identifier: this.data.identifier
        })
        if (res.code !== 20000) return showMsg(res.message)
        console.log(res);
        showMsg('消音下发成功！')
      })
      .catch(() => {});
  },
  // imei查询最新设备数据
  async getDeviceData(e) {
    const res = await reqDeviceData(e.imei)
    if (res.code !== 20000) return showMsg(res.message)
    console.log(res);
    this.setData({
      deviceData: res.data.rows || {}
    })
  },
  // 平面图
  async addbind() {
    const res = await reqFloorById(this.data.deviceInfo.spaceId)
    if (res.code !== 20000) return showMsg(res.message)
    console.log(res);
    if (res.data.rows.image == '') return showMsg('当前楼层暂无平面图，请上传后再标记')
    let info = JSON.stringify(this.data.deviceInfo)
    wx.navigateTo({
      url: `../ichnography/ichnography?id=${this.data.deviceInfo.id}&mark=${this.data.deviceInfo.mark}&image=${res.data.rows.image}&info=${info}`,
    })
  },
  // 告警记录
  onAlarm() {
    let deviceInfo = JSON.stringify(this.data.deviceInfo)
    wx.navigateTo({
      url: `../alarmRecord/alarmRecord?deviceInfo=${deviceInfo}`,
    })
  },
  // 关联业主
  clickProprietor() {
    let info = JSON.stringify(this.data.deviceInfo)
    // console.log(info);
    wx.navigateTo({
      url: `/packageA/pages/index-inside-page/proprietor/proprietor?info=${info}`,
    })
  },
  // 视频监控
  onMonitoring() {
    let info = JSON.stringify({
      ...this.data.deviceInfo,
      accessToken: this.data.accessToken
    })
    if (this.data.deviceInfo.classMark == 'V380') {
      // 宏视
      wx.navigateTo({
        url: `/packageA/pages/index-inside-page/macrovision-camera/macrovision-camera?info=${info}`,
      })
    } else if (this.data.deviceInfo.protocol == '4') {
      // 萤石云
      // wx.navigateTo({
      //     url: `/pages/index-inside-page/device-camera2/device-camera2?info=${info}`,
      // })
      wx.navigateTo({
        url: `/packageA/pages/index-inside-page/live/live?info=${info}`,
      })
    } else {
      // 视洞
      wx.navigateTo({
        url: `/pages/index-inside-page/device-camera/device-camera?info=${info}`,
      })
    }
    // if (this.data.deviceInfo.deviceMac == "" && this.data.deviceInfo.manufacturerId != '1660554046491635714')
    //     return showMsg('设备MAC地址为空')
    // if (this.data.deviceInfo.manufacturerId == '1660554046491635714') {
    //     // 萤石云
    //     wx.navigateTo({
    //         url: `/pages/index-inside-page/device-camera2/device-camera2?info=${info}`,
    //     })
    // } else {
    //     // 视洞
    //     wx.navigateTo({
    //         url: `/pages/index-inside-page/device-camera/device-camera?info=${info}`,
    //     })
    // }
  },
  // 事件回放
  clickHistory() {
    let info = JSON.stringify(this.data.deviceInfo)
    wx.navigateTo({
      url: `/packageA/pages/index-inside-page/history/history?info=${info}`,
    })
  },
  // 告警模式开关
  async onChangeopenDoor(event) {
    this.setData({
      openDoor: event.detail,
    });
    console.log(event.detail);
    const res = await reqBatchDoorSwitch({
      idList: [this.data.deviceInfo.id],
      openDoor: event.detail ? 1 : 0,
      closeDoor: this.data.closeDoor ? 1 : 0
    })
    if (res.code !== 20000) return showMsg(res.message)
  },
  // 告警模式开关
  async onChangecloseDoor(event) {
    this.setData({
      closeDoor: event.detail,
    });
    console.log(this.data.openDoor);
    console.log(event.detail);
    const res = await reqBatchDoorSwitch({
      idList: [this.data.deviceInfo.id],
      openDoor: this.data.openDoor ? 1 : 0,
      closeDoor: event.detail ? 1 : 0
    })
    if (res.code !== 20000) return showMsg(res.message)
  },
  // 只能输入数字 0-100
  handleInput(e) {
    // let serviceValue = e.detail.value.replace(/\D/g, '')
    // if (serviceValue > 100) {
    //     serviceValue = 100
    // }
    this.setData({
      serviceValue: e.detail.value
    })
  },
  // 只能输入数字 1-100
  handleInput2(e) {
    let serviceValue = e.detail.value.replace(/\D/g, '')
    // console.log(serviceValue);
    if (serviceValue === '0') {
      serviceValue = 1
    }
    if (serviceValue > 100) {
      serviceValue = 100
    }
    this.setData({
      serviceValue
    })
  },
  // 获取imei
  getDeviceInfo(e) {
    let item = JSON.parse(e.info)
    if (app.globalData.isProprietor) {
      // 业主
      this.getDeviceUserpage(item.imei)
    } else {
      // 装维
      this.getDeviceList(item.imei)
    }
  },
  // 业主设备列表
  async getDeviceUserpage(imei) {
    const res = await reqDeviceUserpage(1, 10, {
      userId: app.globalData.userId,
      imei: imei
    })
    if (res.code !== 20000) return showMsg(res.message)
    console.log(res);
    let {
      rows
    } = res.data
    this.setData({
      deviceInfo: rows[0]
    })
    if (rows[0].classMark === "SDF300" || rows[0].classMark === "SDF400") {
      this.getDeviceFindInfo()
    }
    // if (this.data.deviceInfo.deviceType == 'SmokeAlarm') {
    //     this.setData({
    //         serviceType: "muffling_cmd",
    //         serviceValue: 1,
    //         serviceTypename: "消音下发",
    //         serviceValuename: "消音",
    //     })
    // } else if (this.data.deviceInfo.deviceType == 'Infrared') {
    //     this.setData({
    //         serviceType: "work_mode",
    //         serviceValue: "0",
    //         serviceTypename: "工作模式",
    //         serviceValuename: "普通模式",
    //     })
    // }
  },
  /**
   * @name: 获取设备列表
   * @return {*}
   */
  async getDeviceList(imei) {
    let params = {
      // orgId: app.globalData.orgId == 1 ? '' : app.globalData.orgId,

      online: '',
      productId: '',
      spaceId: '',
      imei: imei,
      minBattery: '',
      maxBattery: '',
      isAlarm: '',
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
      tenantId: app.globalData.tenantId,
    }
    const res = await reqDeviceList(1, 10, params)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    this.setData({
      deviceInfo: rows[0]
    })
    if (rows[0].classMark === "SDF300" || rows[0].classMark === "SDF400") {
      this.getDeviceFindInfo()
    }
    // console.log('deviceInfo', this.data.deviceInfo);
    // if (this.data.deviceInfo.deviceType == 'SmokeAlarm') {
    //     this.setData({
    //         serviceType: "muffling_cmd",
    //         serviceValue: 1,
    //         serviceTypename: "消音下发",
    //         serviceValuename: "消音",
    //     })
    // } else if (this.data.deviceInfo.deviceType == 'Infrared') {
    //     this.setData({
    //         serviceType: "work_mode",
    //         serviceValue: "0",
    //         serviceTypename: "工作模式",
    //         serviceValuename: "普通模式",
    //     })
    // }
  },
  // 确定指令下发
  async bindtapShoudon() {
    // if (this.data.deviceInfo.deviceId == '') return showMsg('此设备暂不支持下发指令')
    if (this.data.serviceType == '') return showMsg('服务标识不能为空')
    if (this.data.serviceValue == '') return showMsg('服务值不能为空')
    // 首先检查value是否是一个有效的小数
    const reg = /^\d+(\.\d+)?$/;
    if (!reg.test(this.data.serviceValue) && this.data.inputType == 1) return showMsg("请输入正确的服务值范围");
    if (this.data.inputType == 1 && (Number(this.data.serviceValue) > Number(this.data.num2) || Number(this.data.serviceValue) < Number(this.data.num1))) return showMsg('请输入正确的服务值范围')
    const res = await reqCommand({
      deviceId: this.data.deviceInfo.deviceId,
      imei: this.data.deviceInfo.imei,
      serviceType: this.data.serviceType,
      serviceValue: this.data.serviceValue,
      identifier: this.data.identifier
    })
    if (res.code !== 20000) return showMsg(res.message)
    console.log(res);
    showMsg('下发指令成功！')
    this.setData({
      "serviceType": '',
      "serviceTypename": '',
      "serviceValue": "",
      "serviceValuename": "",
      "inputType": 1,
      "identifier": "",
    })
  },
  Clickstatus() {
    this.setData({
      showStatus: true
    })
  },
  Clickstatus2() {
    this.setData({
      showStatus2: true
    })
  },
  // 选择服务标识
  statusConfirm(e) {
    const {
      value,
    } = e.detail;
    console.log(value);
    let dataDefinition;
    let num1;
    let num2;
    let placeholderStr;
    if (value.inputType == 1) {
      num1 = value.dataDefinition.substring(0, value.dataDefinition.indexOf(','))
      num2 = value.dataDefinition.substring(value.dataDefinition.indexOf(',') + 1)
      placeholderStr = `${num1}-${num2}`
    } else {
      dataDefinition = JSON.parse(value.dataDefinition)
    }
    if (this.data.serviceType != value.serviceType) {
      // 切换不同服务标识清空服务值
      this.setData({
        "serviceValue": "",
        "serviceValuename": "",
      })
    }
    this.setData({
      "serviceType": value.serviceType,
      "serviceTypename": value.serviceName,
      showStatus: false,
      "inputType": value.inputType,
      "identifier": value.identifier,
      dataDefinition,
      num1,
      num2,
      placeholderStr,
    })
  },
  statusClose() {
    this.setData({
      showStatus: false
    })
  },
  statusConfirm2(e) {
    const {
      value,
    } = e.detail;
    this.setData({
      "serviceValue": value.value,
      "serviceValuename": value.key,
      showStatus2: false,
    })
  },
  statusClose2() {
    this.setData({
      showStatus2: false
    })
  },
  /**
   * @name:   点击切换 
   * @msg:    1、赋值current 
   * @param {*} e
   * @return {*}
   */
  swichNav(e) {
    let {
      current
    } = e.currentTarget.dataset
    this.setData({
      currentTab: current
    })
    // if (current == 0) {
    //   if (this.data.deviceInfo.classMark === "SDF300" || this.data.deviceInfo.classMark === "SDF400") {
    //     this.getDeviceFindInfo()
    //   }
    // }
  },
  /**
   * @name: 滑动切换
   * @msg:  1、赋值curren
   * @param {*} e
   * @return {*}
   */
  bindChangeTab(e) {
    let {
      current
    } = e.detail
    this.setData({
      currentTab: current
    })
    // if (current == 0) {
    //   if (this.data.deviceInfo.classMark === "SDF300" || this.data.deviceInfo.classMark === "SDF400") {
    //     this.getDeviceFindInfo()
    //   }
    // }
  },
})